package com.supercube.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;


import java.io.InputStream;

/**
 * 七牛工具类
 *
 * @author djzhao
 * @date 19/12/11 22:49
 * @email djzhao627@gmail.com
 */
public class QiNiuUtils {

    //Configuration cfg = new Configuration(Zone.zone2());
    //...其他参数参考类注释
    //		华东	Zone.zone0()
    //		华北	Zone.zone1()
    //		华南	Zone.zone2()
    //		北美	Zone.zoneNa0()

    //构造一个带指定 Region 对象的配置类
    private static Configuration cfg = new Configuration(Region.huadong());
    private static UploadManager uploadManager = new UploadManager(cfg);
    //...生成上传凭证，然后准备上传
    private static final String ACCESS_KEY = "j64_zzPIZo6lp7AqL4fIfljDkI2V68ELqNKll_o3";
    private static final String SECRET_KEY = "8IcMYXrFOK7bQSVbRXDZobs3vH8rAyF0aBRuTUqr";
    private static final String DEFAULT_BUCKET = "madg";


    /**
     * 文件上传（内存中的字节数组上传）
     *
     * @param uploadBytes 字节数组
     * @param fileName    上传使用的文件名<br />
     *                    默认不指定(fileName = null)的情况下，以文件内容的hash值作为文件名
     */
    public static boolean upload(byte[] uploadBytes, String fileName) {
        if (uploadBytes.length == 0) {
            return false;
        }
        // uploadBytes = "hello qiniu cloud".getBytes("utf-8");
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(DEFAULT_BUCKET);
        try {
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return true;
    }


    /**
     * 文件上传（InputStream对象的上传）
     *
     * @param inputStream InputStream对象
     * @param fileName    上传使用的文件名<br />
     *                    默认不指定(fileName = null)的情况下，以文件内容的hash值作为文件名
     */
    public static boolean upload(InputStream inputStream, String fileName) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(DEFAULT_BUCKET);
        try {
            Response response = uploadManager.put(inputStream, fileName, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return true;
    }


    /**
     * 本地上传
     *
     * @param filePath 文件路径
     * @param fileName 上传使用的文件名<br />
     *                 默认不指定(fileName = null)的情况下，以文件内容的hash值作为文件名
     */
    public static void localUpload(String filePath, String fileName) {
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        if (StringUtils.isBlank(filePath)) {
            filePath = "/home/qiniu/test.png";
        }
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(DEFAULT_BUCKET);
        Response response;
        try {
            response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */
    public static int deleteFileFromQiNiu(String fileName) {
        //构造一个带指定Zone对象的配置类
        String key = fileName;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response delete = bucketManager.delete(DEFAULT_BUCKET, key);
            return delete.statusCode;
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            ex.printStackTrace();
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
        return -1;
    }

    /**
     * 获取客户端上传时所需的Token
     *
     * @return token
     */
    public static String getUploadToken() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.uploadToken(DEFAULT_BUCKET);
    }

    /**
     * 获取客户端上传时所需的Token(文件覆盖)
     *
     * @param fileName 需要覆盖的文件名
     * @return token
     */
    public static String getRewriteUploadToken(String fileName) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.uploadToken(DEFAULT_BUCKET, fileName);
    }

    public static void main(String[] args) {
        System.out.println(getUploadToken());
    }

}
